package cn.itcast.order.controller;

import cn.itcast.feign.client.UserClient;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.user.User;
import cn.itcast.order.mapper.OrderMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserClient userClient;
    @PutMapping("/{orderId}")
    public ResultDTO payOrder(@RequestBody String json, @PathVariable Long orderId){
        Long userId = 2L;
        User finduser = userClient.finduser(userId);
        System.out.println(finduser);
        String[] split = json.split(":");
        String password=split[1];
        String[] split1 = password.split("\"");
        password=split1[1];
        System.out.println(password);
        System.err.println("密码："+password);
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        System.out.println(passwordMd5);
        if(!finduser.getPassword().equals(passwordMd5))return ResultDTO.error("登录失败");

        Order order = this.orderMapper.selectById(orderId);
        Integer paymentType = order.getStatus();
        if(paymentType!=1)return ResultDTO.ok("早已支付完成");

        Long totalFee = order.getTotalFee();
        finduser.setBalance(finduser.getBalance()-totalFee);
        boolean b = this.userClient.updateUser(finduser);
        if(!b)return ResultDTO.error("异常");
        //改变订单支付状态
        order.setStatus(2);
        LambdaQueryWrapper<Order> wrapper = Wrappers.<Order>lambdaQuery();
        wrapper.eq(Order::getId,order.getId());
        System.out.println("修改结果");
        System.out.println(orderMapper.update(order, wrapper));
        return ResultDTO.ok("支付完成");
    }
}
